package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.AnswerRecord;
import com.atguigu.exam.entity.ExamRecord;
import com.atguigu.exam.entity.Paper;
import com.atguigu.exam.entity.Question;
import com.atguigu.exam.mapper.ExamRecordMapper;
import com.atguigu.exam.service.AnswerRecordService;
import com.atguigu.exam.service.ExamService;
import com.atguigu.exam.service.KimiAiService;
import com.atguigu.exam.service.PaperService;
import com.atguigu.exam.vo.GradingResult;
import com.atguigu.exam.vo.StartExamVo;
import com.atguigu.exam.vo.SubmitAnswerVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 考试服务实现类
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamService {
    @Autowired
    private PaperService paperService;
    @Autowired
    private KimiAiService kimiAiService;
    @Autowired
    private AnswerRecordService answerRecordService;

    @Override
    public ExamRecord creatNewExam(StartExamVo startExamVo) {
        //校验是否存在正在进行的考试
        LambdaQueryWrapper<ExamRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ExamRecord::getExamId, startExamVo.getPaperId());
        lambdaQueryWrapper.eq(ExamRecord::getStudentName, startExamVo.getStudentName());
        lambdaQueryWrapper.eq(ExamRecord::getStatus, "进行中");
        ExamRecord examRecord = getOne(lambdaQueryWrapper);//根据条件获取考试记录
        if (examRecord != null) {
            log.debug("{}在当前试卷：{}有未完成考试记录！直接返回了！", startExamVo.getStudentName(), startExamVo.getPaperId());
            return examRecord;
        }
        //创建新的考试
        ExamRecord newExamRecord = new ExamRecord();
        newExamRecord.setExamId(startExamVo.getPaperId()); // 设置试卷ID
        newExamRecord.setStudentName(startExamVo.getStudentName()); // 设置考生姓名
        newExamRecord.setStartTime(LocalDateTime.now());
        newExamRecord.setStatus("进行中");
        newExamRecord.setScore(0);
        newExamRecord.setWindowSwitches(0);
        save(newExamRecord);//保存考试记录
        return newExamRecord;
    }

    @Override
    public ExamRecord QueryExamRecord(Integer id) {
        //获取记录
        ExamRecord examRecord = getById(id);
        if (examRecord == null) {
            log.error("考试记录不存在！");
            throw new RuntimeException("编号为:%s的记录不存在".formatted(id));
        }
        //加载试卷信息
        Paper paper = paperService.customPaperById(examRecord.getExamId());
        if (paper == null) {
            throw new RuntimeException("当前考试记录的试卷可能被删除！获取失败！！！");
        }
        //加载答题记录
        LambdaQueryWrapper<AnswerRecord> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(AnswerRecord::getExamRecordId, id);
        List<AnswerRecord> answerRecords = answerRecordService.list(LambdaQueryWrapper);
        //新增：按试卷题目顺序排序答题记录，保证前端展示顺序和考试时一致
        if (!ObjectUtils.isEmpty(answerRecords)) {
            List<Long> list = paper.getQuestions().stream().map(Question::getId).toList();
            answerRecords.sort((a, b) -> {
                int A = list.indexOf(a.getQuestionId().longValue());
                int B = list.indexOf(b.getQuestionId().longValue());
                return Integer.compare(A, B);
            });
        }
        examRecord.setAnswerRecords(answerRecords);
        examRecord.setPaper(paper);
        return examRecord;
    }

    @Override
    public void customSubmitAnswer(Integer examRecordId, List<SubmitAnswerVo> answers) throws InterruptedException {
        //宏观： 提交答案中间表保存  修改考试记录数据（已完成 ，结束时间）  触发开始判卷（examRecordId）
        //1.中间表保存问题
        if (!ObjectUtils.isEmpty(answers)) {
            List<AnswerRecord> answerRecordList = answers.stream().map(vo -> new AnswerRecord(examRecordId, vo.getQuestionId(), vo.getUserAnswer()))
                    .collect(Collectors.toList());
            answerRecordService.saveBatch(answerRecordList);
        }
        //2. 暂时修改下考试记录状态（状态 -》 已完成 || 结束时间 - 设置）
        ExamRecord examRecord = getById(examRecordId);
        examRecord.setEndTime(LocalDateTime.now());
        examRecord.setStatus("已完成");
        updateById(examRecord);

        //3.调用判卷的接口
        gradeExam(examRecordId);
    }

    @Override
    public ExamRecord gradeExam(Integer examRecordId) throws InterruptedException {
        //宏观：  获取考试记录相关的信息（考试记录对象 考试记录答题记录 考试对应试卷）
        //  进行循环判断（1.答题记录进行修改 2.总体提到总分数 总正确数量）  修改考试记录（状态 -》 已批阅  修改 -》 总分数）   进行ai评语生成（总正确的题目数量）
        //  修改考试记录表  返回考试记录对象
        //1.获取考试记录和相关的信息（试卷和答题记录）
        ExamRecord examRecord = QueryExamRecord(examRecordId);
        Paper paper = examRecord.getPaper();
        if (paper == null){
            examRecord.setStatus("已批阅");
            examRecord.setAnswers("考试对应的试卷被删除！无法进行成绩判定！");
            updateById(examRecord);
            throw new RuntimeException("考试对应的试卷被删除！无法进行成绩判定！");
        }
        List<AnswerRecord> answerRecords = examRecord.getAnswerRecords();
        if (ObjectUtils.isEmpty(answerRecords)){
            //没有提交
            examRecord.setStatus("已批阅");
            examRecord.setScore(0);
            examRecord.setAnswers("没有提交记录！成绩为零！继续加油！");
            updateById(examRecord);
            return examRecord;
        }

        //2.进行循环的判卷（1.记录总分数 2.记录正确题目数量 3. 修改每个答题记录的状态（得分，是否正确 0 1 2 ，text-》ai评语））
        int correctNumber = 0 ; //正确题目数量
        int totalScore = 0; //总得分

        //报错继续！ 某个记录错了，后续还需要继续判卷
        //将正确题目转成map,方便每次判断获取正确答案
        Map<Long, Question> questionMap = paper.getQuestions().stream().collect(Collectors.toMap(Question::getId, q -> q));

        for (AnswerRecord answerRecord : answerRecords) {
            try {
                //1.先获取 答题记录对应的题目对象
                Question question = questionMap.get(answerRecord.getQuestionId().longValue());
                String systemAnswer = question.getAnswer().getAnswer();
                String userAnswer = answerRecord.getUserAnswer();
                if ("JUDGE".equalsIgnoreCase(question.getType())){
                    //true false
                    userAnswer = normalizeJudgeAnswer(userAnswer);
                }
                if (!"TEXT".equals(question.getType())) {
                    //2.判断题目类型(选择和判断直接判卷)
                    if (systemAnswer.equalsIgnoreCase(userAnswer)){
                        answerRecord.setIsCorrect(1); //正确
                        answerRecord.setScore(question.getPaperScore().intValue());
                    }else{
                        answerRecord.setIsCorrect(0); //正确
                        answerRecord.setScore(0);
                    }
                }else{
                    //3.简答题进行ai判断
                    //简答题
                    GradingResult result =
                            kimiAiService.gradingTextQuestion(question,userAnswer,question.getPaperScore().intValue());

                    //分
                    answerRecord.setScore(result.getScore());
                    //ai评价 正确  feedback  非正确 reason
                    //是否正确 （满分 1 0分 0 其余就是2）
                    if (result.getScore() == 0){
                        answerRecord.setIsCorrect(0);
                        answerRecord.setAiCorrection(result.getReason());
                    }else if (result.getScore() == question.getPaperScore().intValue()){
                        answerRecord.setIsCorrect(1);
                        answerRecord.setAiCorrection(result.getFeedback());
                    }else{
                        answerRecord.setIsCorrect(2);
                        answerRecord.setAiCorrection(result.getReason());
                    }
                }
            } catch (Exception e) {
                answerRecord.setScore(0);
                answerRecord.setIsCorrect(0);
                answerRecord.setAiCorrection("判题过程出错！");
            }
            //进行记录修改
            //进行总分数赋值
            totalScore += answerRecord.getScore();
            //正确题目数量累加
            if (answerRecord.getIsCorrect() == 1){
                correctNumber++;
            }
        }
        answerRecordService.updateBatchById(answerRecords);

        //进行ai生成评价，进行考试记录修改和完善
        String summary = kimiAiService.
                buildSummary(totalScore, paper.getTotalScore().intValue(), paper.getQuestionCount(), correctNumber);

        examRecord.setScore(totalScore);
        examRecord.setAnswers(summary);
        examRecord.setStatus("已批阅");
        updateById(examRecord);

        return examRecord;
    }


    /**
     * 标准化判断题答案，将T/F转换为TRUE/FALSE
     * @param answer 原始答案
     * @return 标准化后的答案
     */
    private String normalizeJudgeAnswer(String answer) {
        if (answer == null || answer.trim().isEmpty()) {
            return "";
        }

        String normalized = answer.trim().toUpperCase();
        switch (normalized) {
            case "T":
            case "TRUE":
            case "正确":
                return "TRUE";
            case "F":
            case "FALSE":
            case "错":
                return "FALSE";
            default:
                return normalized;
        }
    }
}